import json

class PmuConfig:
    def __init__(self, pmu_cfg):
        self.pmu_data = {
            'event_num' : 0,
            'umask' : 0,
            'user' : 1,
            'os' : 0,
            'edge' : 0,
            'pc' : 0,
            'api_init' : 0,
            'any_core' : 0,
            'enable' : 1,
            'inv' : 0,
            'cmask' : 0
        }

        for key in pmu_cfg.keys():
            self.pmu_data[key] = int(pmu_cfg[key], 16)
    
    @property
    def value(self):
        data = 0
        data |= self.pmu_data['cmask'] << 24
        data |= self.pmu_data['inv'] << 23
        data |= self.pmu_data['enable'] << 22
        data |= self.pmu_data['any_core'] << 21
        data |= self.pmu_data['edge'] << 18
        data |= self.pmu_data['os'] << 17
        data |= self.pmu_data['user'] << 16
        data |= self.pmu_data['umask'] << 8
        data |= self.pmu_data['event_num']
        return data

    @staticmethod
    def get_pmu_data_by_json(file_name):
        pmu_data = {'rdtsc': 0, 'cycles': 1, 'instructions': 2}
        with open(file_name) as f:
            pmu_json = json.load(f)
            for name, value in pmu_json.items():
                pmu_data[name] = PmuConfig(value).value
        return pmu_data
    
    @staticmethod
    def getpmu_data_by_input():
        pass

    

if __name__ == "__main__":
    pmu_data = PmuConfig.get_pmu_data_by_json("pmu.json")
    with open('pmu_events', 'w') as f:
        f.write('%d\n' % len(pmu_data))
        for name, value in pmu_data.items():
            f.write('%s %x\n' % (name, value))
    print('success to generate "pmu_events" by "pmu.json".')
